import pickle
import time

import pymysql
import redis

# 数据库取值
def load_depts_from_db():
    # 连接数据库
    conn = pymysql.connect(host='localhost', port=3306,
                           user='root', password='123456',
                           database='hrs', charset='utf8')
    depts = ()
    try:
        # 数据库操作，拿到游标对象
        with conn.cursor() as cursor:
            cursor.execute('select dno,dname, dloc from tb_dept')
            # fecthall()返回多个纪录，若没有则返回空
            depts = cursor.fetchall()
    #捕获异常
    except pymysql.MySQLError as err:
        print(err)
    finally:
        conn.close()
    #返回结果
    return depts

def main():
    # 连接Redis
    client = redis.Redis(host='47.107.87.249', port=6379, password='1234')
    start = time.time()
    # 获取Redis中数据
    data = client.get('depts')
    if data:
        # 解压 字节串
        depts = pickle.loads(data)
    else:
        # 调用数据库查找
        depts = load_depts_from_db()
        # 写入缓存
        client.set('depts',pickle.dumps(depts))
    end = time.time()
    print(depts)
    print(f'执行时间：{end-start}秒')

if __name__ == '__main__':
    main()
